use std::{f32::INFINITY, ops::{Mul, Div}};

use super::{vector2::{Point2, pos2, Size2, size2, Vec2, vec2}, range::Rangef, lerp};


/// A rectangular region of space.
///
/// Usually a [`Rect`] has a positive (or zero) size,
/// and then [`Self::min`] `<=` [`Self::max`].
/// In these cases [`Self::min`] is the left-top corner
/// and [`Self::max`] is the right-bottom corner.
///
/// A rectangle is allowed to have a negative size, which happens when the order
/// of `min` and `max` are swapped. These are usually a sign of an error.
///
/// Normally the unit is points (logical pixels) in screen space coordinates.
///
/// `Rect` does NOT implement `Default`, because there is no obvious default value.
/// [`Rect::ZERO`] may seem reasonable, but when used as a bounding box, [`Rect::NOTHING`]
/// is a better default - so be explicit instead!
#[repr(C)]
#[derive(Clone, Copy, Eq, PartialEq,Default)]
pub struct Rect {
    /// One of the corners of the rectangle, usually the left top one.
    pub pos: Point2,

    /// The other corner, opposing [`Self::min`]. Usually the right bottom one.
    pub size: Point2,
}

impl Rect {
    pub fn new(x:f32,y: f32,w: f32,h: f32) -> Self {
        Self { pos: pos2(x, y), size: size2(w, h) }
    }
    /// Infinite rectangle that contains every point.
    pub const EVERYTHING: Self = Self {
        pos: Point2{x:-INFINITY, y:-INFINITY},
        size: Size2{x:INFINITY, y:INFINITY},
    };
    #[inline]
    pub fn min(&self) -> Point2 {
        self.pos
    }
    #[inline]
    pub fn max(&self) -> Point2 {

        let max_x = if self.size.x == f32::INFINITY {
            f32::INFINITY
        }else {
            self.pos.x + self.size.x
        };

        let max_y = if self.size.y == f32::INFINITY {
            f32::INFINITY
        }else {
            self.pos.y + self.size.y
        };

        pos2(max_x, max_y)
    }

    #[inline]
    pub fn is_zero(&self) -> bool {
        self.size.x == 0.0 && self.size.y == 0.0
    }

    /// The inverse of [`Self::EVERYTHING`]: stretches from positive infinity to negative infinity.
    /// Contains no points.
    ///
    /// This is useful as the seed for bounding boxes.
    ///
    /// # Example:
    /// ```
    /// # use emath::*;
    /// let mut rect = Rect::NOTHING;
    /// assert!(rect.size() == Vec2::splat(-f32::INFINITY));
    /// assert!(rect.contains(pos2(0.0, 0.0)) == false);
    /// rect.extend_with(pos2(2.0, 1.0));
    /// rect.extend_with(pos2(0.0, 3.0));
    /// assert_eq!(rect, Rect::from_min_max(pos2(0.0, 1.0), pos2(2.0, 3.0)))
    /// ```
    pub const NOTHING: Self = Self {
        pos: Point2{x:INFINITY, y:INFINITY},
        size:  Size2{x:-INFINITY, y:-INFINITY},

    };

    /// An invalid [`Rect`] filled with [`f32::NAN`].
    pub const NAN: Self = Self {
        pos: Point2{x:f32::NAN, y:f32::NAN},
        size:  Size2{x:f32::NAN, y:f32::NAN},

    };

    /// A [`Rect`] filled with zeroes.
    pub const ZERO: Self = Self {
        pos: Point2::ZERO,
        size: Size2::ZERO,
    };

    #[inline(always)]
    pub  fn from_min_max(min: Point2, max: Point2) -> Self {
        Rect { pos:min, size:Size2 {
            x: max.x - min.x,
            y: max.y - min.y,
        } }
    }

    /// left-top corner plus a size (stretching right-down).
    #[inline(always)]
    pub fn from_min_size(min: Point2, size: Size2) -> Self {
        Rect {
            pos:min,
            size,
        }
    }

    #[inline(always)]
    pub fn from_center_size(center: Point2, size: Size2) -> Self {
        Rect {
            pos: center - size * 0.5,
            size
        }
    }

    #[inline(always)]
    pub fn from_x_y_ranges(x_range: impl Into<Rangef>, y_range: impl Into<Rangef>) -> Self {
        let x_range = x_range.into();
        let y_range = y_range.into();
    
        Rect {
            pos: pos2(x_range.min, y_range.min),
            size: size2(x_range.max - x_range.min, y_range.max - y_range.min),
        }
    }

    /// Returns the bounding rectangle of the two points.
    #[inline]
    pub fn from_two_pos(a: Point2, b: Point2) -> Self {
        let min_x = a.x.min(b.x);
        let min_y = a.y.min(b.y);
        Rect {
            pos: pos2(min_x, min_y),
            size: size2(a.x.max(b.x) - min_x, a.y.max(b.y) - min_y),
        }
    }

    /// Bounding-box around the points.
    pub fn from_points(points: &[Point2]) -> Self {
        let mut rect = Rect::NOTHING;
        for &p in points {
            rect.extend_with(p);
        }
        rect
    }

    /// A [`Rect`] that contains every point to the right of the given X coordinate.
    #[inline]
    pub fn everything_right_of(left_x: f32) -> Self {
        let mut rect = Self::EVERYTHING;
        rect.set_left(left_x);
        rect
    }

    /// A [`Rect`] that contains every point to the left of the given X coordinate.
    #[inline]
    pub fn everything_left_of(right_x: f32) -> Self {
        let mut rect = Self::EVERYTHING;
        rect.set_right(right_x);
        rect
    }

    /// A [`Rect`] that contains every point below a certain y coordinate
    #[inline]
    pub fn everything_below(top_y: f32) -> Self {
        let mut rect = Self::EVERYTHING;
        rect.set_top(top_y);
        rect
    }

    /// A [`Rect`] that contains every point above a certain y coordinate
    #[inline]
    pub fn everything_above(bottom_y: f32) -> Self {
        let mut rect = Self::EVERYTHING;
        rect.set_bottom(bottom_y);
        rect
    }

    #[must_use]
    #[inline]
    pub fn with_min_x(mut self, min_x: f32) -> Self {
        self.pos.x = min_x;
        self
    }

    #[must_use]
    #[inline]
    pub fn with_min_y(mut self, min_y: f32) -> Self {
        self.pos.y = min_y;
        self
    }

    #[must_use]
    #[inline]
    pub fn with_max_x(mut self, max_x: f32) -> Self {
        self.size.x = max_x - self.pos.x;
        self
    }

    #[must_use]
    #[inline]
    pub fn with_max_y(mut self, max_y: f32) -> Self {
        self.size.y = max_y - self.pos.y;
        self
    }

    /// Expand by this much in each direction, keeping the center
    #[must_use]
    pub fn expand(self, amnt: f32) -> Self {
        self.expand2(Vec2::splat(amnt))
    }

    /// Expand by this much in each direction, keeping the center
    #[must_use]
    pub fn expand2(self, amnt: Vec2) -> Self {
        Rect::from_min_max(self.pos - amnt, self.max() + amnt)
    }

    /// Shrink by this much in each direction, keeping the center
    #[must_use]
    pub fn shrink(self, amnt: f32) -> Self {
        self.shrink2(Vec2::splat(amnt))
    }

    /// Shrink by this much in each direction, keeping the center
    #[must_use]
    pub fn shrink2(self, amnt: Vec2) -> Self {
        Rect::from_min_max(self.pos + amnt, self.max() - amnt)
    }

    #[must_use]
    #[inline]
    pub fn translate(self, amnt: Vec2) -> Self {
        Rect::from_min_size(self.pos + amnt, self.size())
    }

    // /// Rotate the bounds (will expand the [`Rect`])
    // #[must_use]
    // #[inline]
    // pub fn rotate_bb(self, rot: Rot2) -> Self {
    //     let a = rot * self.left_top();
    //     let b = rot * self.right_top();
    //     let c = rot * self.left_bottom();
    //     let d = rot * self.right_bottom();

    //     Self::from_min_max(
    //         a.min(b).min(c).min(d),
    //         a.max(b).max(c).max(d),
    //     )
    // }

    #[must_use]
    #[inline]
    pub fn intersects(self, other: Rect) -> bool {

    
        self.pos.x <= other.max().x
            && other.pos.x <= self.max().x
            && self.pos.y <= other.max().y
            && other.pos.y <= self.max().y
    }

    /// keep min
    pub fn set_width(&mut self, w: f32) {
        self.size.x = w;
    }

    /// keep min
    pub fn set_height(&mut self, h: f32) {
        self.size.y =  h;
    }

    /// Keep size
    pub fn set_center(&mut self, center: Point2) {
        *self = self.translate(center - self.center());
    }

    #[must_use]
    #[inline(always)]
    pub fn contains(&self, p: Point2) -> bool {
        self.pos.x <= p.x && p.x <= self.max().x && self.pos.y <= p.y && p.y <= self.max().y
    }

    #[must_use]
    pub fn contains_rect(&self, other: Rect) -> bool {
        self.contains(other.pos) && self.contains(other.max())
    }

    /// Return the given points clamped to be inside the rectangle
    /// Panics if [`Self::is_negative`].
    #[must_use]
    pub fn clamp(&self, p: Point2) -> Point2 {
        p.clamp(self.pos, self.max())
    }

    #[inline(always)]
    pub fn extend_with(&mut self, p: Point2) {
        let max = self.max().max(p);
        self.pos = self.pos.min(p);
        self.size = max - self.pos;
    }

    #[inline(always)]
    /// Expand to include the given x coordinate
    pub fn extend_with_x(&mut self, x: f32) {
        let max = self.max().x.max(x);
        self.pos.x = self.pos.x.min(x);
        self.size.x = max - self.pos.y;
    }

    #[inline(always)]
    /// Expand to include the given y coordinate
    pub fn extend_with_y(&mut self, y: f32) {
        let max = self.max().y.max(y);
        self.pos.y = self.pos.y.min(y);
        self.size.y = max - self.pos.y;
    }

    /// The union of two bounding rectangle, i.e. the minimum [`Rect`]
    /// that contains both input rectangles.
    #[inline(always)]
    #[must_use]
    pub fn union(self, other: Rect) -> Rect {
        let pos = self.pos.min(other.pos);
        let max = self.max().max(other.max());
        Rect {
            pos,
            size: max - pos,
        }
    }

    /// The intersection of two [`Rect`], i.e. the area covered by both.
    #[inline]
    #[must_use]
    pub fn intersect(self, other: Rect) -> Self {
        let pos = self.pos.max(other.pos);
        let max = self.max().min(other.max());
       
        Self {
            pos,
            size: max - pos,
        }
    }

    #[inline(always)]
    pub fn center(&self) -> Point2 {
        Point2 {
            x: (self.pos.x + self.max().x) / 2.0,
            y: (self.pos.y + self.max().y) / 2.0,
        }
    }

    /// `rect.size() == Vec2 { x: rect.width(), y: rect.height() }`
    #[inline(always)]
    pub fn size(&self) -> Vec2 {
        self.size
    }

    #[inline(always)]
    pub fn width(&self) -> f32 {
        self.size.x
    }

    #[inline(always)]
    pub fn height(&self) -> f32 {
        self.size.y
    }

    /// Width / height
    ///
    /// * `aspect_ratio < 1`: portrait / high
    /// * `aspect_ratio = 1`: square
    /// * `aspect_ratio > 1`: landscape / wide
    pub fn aspect_ratio(&self) -> f32 {
        self.width() / self.height()
    }

    /// `[2, 1]` for wide screen, and `[1, 2]` for portrait, etc.
    /// At least one dimension = 1, the other >= 1
    /// Returns the proportions required to letter-box a square view area.
    pub fn square_proportions(&self) -> Vec2 {
        let w = self.width();
        let h = self.height();
        if w > h {
            vec2(w / h, 1.0)
        } else {
            vec2(1.0, h / w)
        }
    }

    #[inline(always)]
    pub fn area(&self) -> f32 {
        self.width() * self.height()
    }

    /// The distance from the rect to the position.
    ///
    /// The distance is zero when the position is in the interior of the rectangle.
    #[inline]
    pub fn distance_to_pos(&self, pos: Point2) -> f32 {
        self.distance_sq_to_pos(pos).sqrt()
    }

    /// The distance from the rect to the position, squared.
    ///
    /// The distance is zero when the position is in the interior of the rectangle.
    #[inline]
    pub fn distance_sq_to_pos(&self, pos: Point2) -> f32 {
        let dx = if self.pos.x > pos.x {
            self.pos.x - pos.x
        } else if pos.x > self.max().x {
            pos.x - self.max().x
        } else {
            0.0
        };

        let dy = if self.pos.y > pos.y {
            self.pos.y - pos.y
        } else if pos.y > self.max().y {
            pos.y - self.max().y
        } else {
            0.0
        };

        dx * dx + dy * dy
    }

    /// Signed distance to the edge of the box.
    ///
    /// Negative inside the box.
    ///
    /// ```
    /// # use emath::{pos2, Rect};
    /// let rect = Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0));
    /// assert_eq!(rect.signed_distance_to_pos(pos2(0.50, 0.50)), -0.50);
    /// assert_eq!(rect.signed_distance_to_pos(pos2(0.75, 0.50)), -0.25);
    /// assert_eq!(rect.signed_distance_to_pos(pos2(1.50, 0.50)), 0.50);
    /// ```
    pub fn signed_distance_to_pos(&self, pos: Point2) -> f32 {
        let edge_distances = (pos - self.center()).abs() - self.size() * 0.5;
        let inside_dist = edge_distances.max_elem().min(0.0);
        let outside_dist = edge_distances.max(Vec2::ZERO).length();
        inside_dist + outside_dist
    }

    /// Linearly interpolate so that `[0, 0]` is [`Self::min`] and
    /// `[1, 1]` is [`Self::max`].
    pub fn lerp_inside(&self, t: Vec2) -> Point2 {
        Point2 {
            x: lerp(self.pos.x..=self.max().x, t.x),
            y: lerp(self.pos.y..=self.max().y, t.y),
        }
    }

    /// Linearly self towards other rect.
    pub fn lerp_towards(&self, other: &Rect, t: f32) -> Self {
        Self {
            pos: self.pos.lerp(other.pos, t),
            size: self.size.lerp(other.size, t),
        }
    }

    #[inline(always)]
    pub fn x_range(&self) -> Rangef {
        Rangef::new(self.pos.x, self.max().x)
    }

    #[inline(always)]
    pub fn y_range(&self) -> Rangef {
        Rangef::new(self.pos.y, self.max().y)
    }

    #[inline(always)]
    pub fn bottom_up_range(&self) -> Rangef {
        Rangef::new(self.max().y, self.pos.y)
    }

    /// `width < 0 || height < 0`
    #[inline(always)]
    pub fn is_negative(&self) -> bool {
        self.max().x < self.pos.x || self.max().y < self.pos.y
    }

    /// `width > 0 && height > 0`
    #[inline(always)]
    pub fn is_positive(&self) -> bool {
        self.size.x > 0.0 && self.size.y > 0.0
    }

    /// True if all members are also finite.
    #[inline(always)]
    pub fn is_finite(&self) -> bool {
        self.pos.is_finite() && self.size.is_finite()
    }

    /// True if any member is NaN.
    #[inline(always)]
    pub fn any_nan(self) -> bool {
        self.pos.any_nan() || self.size.any_nan()
    }
}

/// ## Convenience functions (assumes origin is towards left top):
impl Rect {
    /// `min.x`
    #[inline(always)]
    pub fn left(&self) -> f32 {
        self.pos.x
    }

    /// `min.x`
    #[inline(always)]
    pub fn left_mut(&mut self) -> &mut f32 {
        &mut self.pos.x
    }

    /// `min.x`
    #[inline(always)]
    pub fn set_left(&mut self, x: f32) {
        self.pos.x = x;
    }

    /// `max.x`
    #[inline(always)]
    pub fn right(&self) -> f32 {
        self.max().x
    }

    /// `max.x`
    // #[inline(always)]
    // pub fn right_mut(&mut self) -> &mut f32 {
    //     &mut self.max.x
    // }

    /// `max.x`
    #[inline(always)]
    pub fn set_right(&mut self, x: f32) {
        self.size.x = x - self.pos.x;
    }

    /// `min.y`
    #[inline(always)]
    pub fn top(&self) -> f32 {
        self.pos.y
    }

    /// `min.y`
    #[inline(always)]
    pub fn top_mut(&mut self) -> &mut f32 {
        &mut self.pos.y
    }

    /// `min.y`
    #[inline(always)]
    pub fn set_top(&mut self, y: f32) {
        self.pos.y = y;
    }

    /// `max.y`
    #[inline(always)]
    pub fn bottom(&self) -> f32 {
        self.max().y
    }

    /// `max.y`
    // #[inline(always)]
    // pub fn bottom_mut(&mut self) -> &mut f32 {
    //     &mut self.max().y
    // }

    /// `max.y`
    #[inline(always)]
    pub fn set_bottom(&mut self, y: f32) {
        self.size.y = y - self.pos.y;
    }

    #[inline(always)]
    pub fn left_top(&self) -> Point2 {
        pos2(self.left(), self.top())
    }

    #[inline(always)]
    pub fn center_top(&self) -> Point2 {
        pos2(self.center().x, self.top())
    }

    #[inline(always)]
    pub fn right_top(&self) -> Point2 {
        pos2(self.right(), self.top())
    }

    #[inline(always)]
    pub fn left_center(&self) -> Point2 {
        pos2(self.left(), self.center().y)
    }

    #[inline(always)]
    pub fn right_center(&self) -> Point2 {
        pos2(self.right(), self.center().y)
    }

    #[inline(always)]
    pub fn left_bottom(&self) -> Point2 {
        pos2(self.left(), self.bottom())
    }

    #[inline(always)]
    pub fn center_bottom(&self) -> Point2 {
        pos2(self.center().x, self.bottom())
    }

    #[inline(always)]
    pub fn right_bottom(&self) -> Point2 {
        pos2(self.right(), self.bottom())
    }

    /// Split rectangle in left and right halves. `t` is expected to be in the (0,1) range.
    pub fn split_left_right_at_fraction(&self, t: f32) -> (Rect, Rect) {
        self.split_left_right_at_x(lerp(self.pos.x..=self.max().x, t))
    }

    /// Split rectangle in left and right halves at the given `x` coordinate.
    pub fn split_left_right_at_x(&self, split_x: f32) -> (Rect, Rect) {
        let left = Rect::from_min_max(self.pos, Point2::new(split_x, self.max().y));
        let right = Rect::from_min_max(Point2::new(split_x, self.pos.y), self.max());
        (left, right)
    }

    /// Split rectangle in top and bottom halves. `t` is expected to be in the (0,1) range.
    pub fn split_top_bottom_at_fraction(&self, t: f32) -> (Rect, Rect) {
        self.split_top_bottom_at_y(lerp(self.pos.y..=self.max().y, t))
    }

    /// Split rectangle in top and bottom halves at the given `y` coordinate.
    pub fn split_top_bottom_at_y(&self, split_y: f32) -> (Rect, Rect) {
        let top = Rect::from_min_max(self.pos, Point2::new(self.max().x, split_y));
        let bottom = Rect::from_min_max(Point2::new(self.pos.x, split_y), self.max());
        (top, bottom)
    }

   
}

impl Rect {
    #[inline]
    pub fn merge(&self , rect:&Rect) -> Self {
        let mut new_rect = Self::default();

        new_rect.pos.x = rect.pos.x.min(self.pos.x);
        new_rect.pos.y = rect.pos.y.min(self.pos.y);
        new_rect.size.x = (rect.pos.x +rect.size.x).max(self.pos.x +self.size.x);
   
        new_rect.size.y = (rect.pos.y +rect.size.y).max(self.pos.y +self.size.y);

        new_rect
    }


    #[inline]
    pub fn intersection(&self , p_rect:&Rect) -> Self {
        let mut new_rect = Self::default();

		if !self.intersects(new_rect) {
			return Self::default();
		}

		new_rect.pos.x = p_rect.pos.x.max(self.pos.x);
		new_rect.pos.y = p_rect.pos.y.max(self.pos.y);

		let p_rect_end = p_rect.pos + p_rect.size;
		let end = self.pos + self.size;

		new_rect.size.x = p_rect_end.x.min(end.x) - new_rect.pos.x;
		new_rect.size.y = p_rect_end.y.min(end.y) - new_rect.pos.y;

		return new_rect;
	}

    pub fn to_col_array(&self) -> [f32;4] {
        [self.pos.x,self.pos.y,self.size.x,self.size.y]
    }
}

impl std::fmt::Debug for Rect {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "[{:?} - {:?}]", self.pos, self.size)
    }
}

/// from (min, max) or (left top, right bottom)
impl From<[Point2; 2]> for Rect {
    fn from([min, max]: [Point2; 2]) -> Self {
        Self { pos:min, size:max - min }
    }
}

impl Mul<f32> for Rect {
    type Output = Rect;

    #[inline]
    fn mul(self, factor: f32) -> Rect {
        Rect {
            pos: self.pos * factor,
            size: self.size * factor,
        }
    }
}

impl Mul<Rect> for f32 {
    type Output = Rect;

    #[inline]
    fn mul(self, vec: Rect) -> Rect {
        Rect {
            pos: self * vec.pos,
            size: self * vec.size,
        }
    }
}

impl Div<f32> for Rect {
    type Output = Rect;

    #[inline]
    fn div(self, factor: f32) -> Rect {
        Rect {
            pos: self.pos / factor,
            size: self.size / factor,
        }
    }
}


